package com.chenyi.web.controller.system;

import com.chenyi.common.annotation.Log;
import com.chenyi.common.constant.UserConstants;
import com.chenyi.common.core.controller.BaseController;
import com.chenyi.common.core.domain.entity.SysAdminDept;
import com.chenyi.common.enums.BusinessType;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.system.service.ISysAdminDeptService;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 * 
 * @author wangkh
 */
@RestController
@RequestMapping("/admin/dept")
public class AdminDeptController extends BaseController
{
    @Autowired
    private ISysAdminDeptService deptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@admin.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public ResponseEntity<Object> list(SysAdminDept dept)
    {
        List<SysAdminDept> depts = deptService.selectAdminDeptList(dept);
        return ResponseEntity.ok(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@admin.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public ResponseEntity<Object> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysAdminDept> depts = deptService.selectAdminDeptList(new SysAdminDept());
        Iterator<SysAdminDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysAdminDept d = (SysAdminDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return ResponseEntity.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@admin.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public ResponseEntity<Object> getInfo(@PathVariable Long deptId)
    {
        return ResponseEntity.ok(deptService.selectAdminDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public ResponseEntity<Object> treeselect(SysAdminDept dept)
    {
        List<SysAdminDept> depts = deptService.selectAdminDeptList(dept);
        return ResponseEntity.ok(deptService.buildAdminDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public ResponseEntity<Object> roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysAdminDept> depts = deptService.selectAdminDeptList(new SysAdminDept());
        Map<String,Object> data = Maps.newHashMap();
        data.put("checkedKeys", deptService.selectAdminDeptListByRoleId(roleId));
        data.put("depts", deptService.buildAdminDeptTreeSelect(depts));
        return ResponseEntity.ok(data);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@admin.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseEntity<Object> add(@Validated @RequestBody SysAdminDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkAdminDeptNameUnique(dept)))
        {
            throw new MessageException("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(AdminUtils.getUsername());
        deptService.insertAdminDept(dept);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@admin.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseEntity<Object> edit(@Validated @RequestBody SysAdminDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkAdminDeptNameUnique(dept)))
        {
            throw new MessageException("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            throw new MessageException("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenAdminDeptById(dept.getDeptId()) > 0)
        {
            throw new MessageException("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(AdminUtils.getUsername());
        deptService.updateAdminDept(dept);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@admin.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public ResponseEntity<Object> remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            throw new MessageException("存在下级部门,不允许删除");
        }
        if (deptService.checkAdminDeptExistUser(deptId))
        {
            throw new MessageException("部门存在用户,不允许删除");
        }
        deptService.deleteAdminDeptById(deptId);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
